﻿using FreeSql;
using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Mvc;
using orm.freesql.api.Entities;

namespace orm.freesql.api.Controllers
{
    /// <summary>
    /// 多表操作（核心是导航属性，虽然约定的命名可以不使用导航特性标记，但建议使用）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MultipleController : ControllerBase
    {
        public IBaseRepository<Order> OrderRepository { get; }

        public MultipleController(IBaseRepository<Order> orderRepository)
        {
            OrderRepository = orderRepository;
            OrderRepository.DbContextOptions.EnableCascadeSave = true; // 开启级联
        }

        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now,
                OrderDetails =
                [
                    new()
                    {
                        ProductName = "导航新增",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    },
                    new()
                    {
                        ProductName = "导航新增2",
                        ProductPrice = 1.1m,
                        CreateTime = DateTime.Now
                    }
                ]
            };

            var result = await OrderRepository.InsertAsync(order);
            return Ok("Id：" + result.Id);
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            var order = await OrderRepository
                .Select
                .IncludeMany(o => o.OrderDetails)
                .Where(o => o.Id == id)
                .FirstAsync();

            return Ok(await OrderRepository.DeleteAsync(order) > 0);
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            var pageInfo = new BasePagingInfo
            {
                PageNumber = pageIndex,
                PageSize = pageSize
            };

            var orders = await OrderRepository
                .Select
                .IncludeMany(o => o.OrderDetails)
                .Where(o => o.IsDeleted == false)
                .OrderByDescending(o => o.Id)
                .Page(pageInfo)
                .ToListAsync();

            return Ok(new { rows = orders, total = pageInfo.Count });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await OrderRepository
                .Select
                .IncludeMany(o => o.OrderDetails)
                .Where(o => o.Id == id)
                .FirstAsync());
        }
    }
}
